<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //方法一 倒序遍历
        function fn1(num) {
            num += '';
            let result = '';
            num = num.split('').reverse();
            num.forEach((item, i) => {
                result = item + result;
                // 3.每隔3位加一个逗号
                if (i % 3 === 2 && i !== num.length - 1) {
                    result = ',' + result;
                }
            });
            console.log(result);
            return result;
        }
        fn1(12115)


        // 方法二分开处理
        function fn2(num) {
            const len = num.length;
            // 获取剩余长度
            const remainderLen = len % 3;
            // 取出剩余字符串
            const result = remainderLen ? [num.substring(0, remainderLen)] : [];
            // 对其余长度是3的倍数的字符做遍历
            for (let i = remainderLen; i < len; i += 3) {
                result.push(num.substring(i, i + 3));
            }
            console.log(result.join(','));
            return result.join(',');
        }
        fn2(21556)

        // 方法三 正则
        function fn3(num) {
            const result = num.replace(/(?<!^)(?=(\d{3})+$)/g, ',');
            console.log(result);
            return result;
        }
        fn3(65445)
    </script>
</body>

</html>